<?php
// $Id$

/**
 */
class Controller_Admin_Customer extends Controller_Abstract
{
    function actionGenMoreWaitingList()
    {
        $c = Customer::findById($this->_context->customer_id)->getOne();

        $newWaitingList = new QColl('Mail_Waiting');

        try {
            foreach ($c->mailAddressPlans as $addressPlan) {
                if($addressPlan->status == Mail_Address_Plan::PLAN_STATUS_PAUSED) continue;
                $newWaitingList->append($addressPlan->genMails(array('qtyToGen' => 10)));
            }

            $newWaitingListData = array();

            foreach ($newWaitingList as $waitingMail) {
                $newWaitingListData[] = array(
                    'to' => $waitingMail->to,
                    'subject' => $waitingMail->subject,
                    'send_date' => $waitingMail->send_date,
                    'send_time' => $waitingMail->send_time,
                );
            }

            $ret = array(
                'ack' => 'success',
                'waitingList' => $newWaitingListData,
            );
        } catch (Exception $e){
            $ret = array(
                'ack' => 'error',
                'msg' => $e->getMessage(),
            );
        }

        return json_encode($ret);

    }

    function actionWaitingList()
    {
        $c = Customer::findById($this->_context->customer_id)->getOne();
        $waitingList = array();

        foreach ($c->waitingList as $waitingMail) {
            $waitingList[] = array(
                'to' => $waitingMail->to,
                'subject' => $waitingMail->subject,
                'send_date' => $waitingMail->send_date,
                'send_time' => $waitingMail->send_time,
            );
        }

        $ret = array(
            'ack' => 'success',
            'waitingList' => $waitingList,
        );

        return json_encode($ret);
    }

    function actionIndex()
    {
        $select = Customer::find();

        if($this->_context->country_id){
            $select->where('country_id=?',$this->_context->country_id);
        }

        if($this->_context->profession_id){
            $select->where('profession_id=?',$this->_context->profession_id);
        }

        if($this->_context->grade || $this->_context->grade === '0' ){
            $select->where('grade=?',$this->_context->grade);
        }

        if($this->_context->customer_num){
            $select->where('customer_num like ?','%'.$this->_context->customer_num.'%');
        }

        if($this->_context->full_name){
            $select->where('full_name like ?','%'.$this->_context->full_name.'%');
        }

        if($this->_context->bindPlanStatus === '0'){
            // find all customer id that has no plan binded
            $res = QDB::getConn()->getAll('select distinct c.customer_id from customer c left join mail_address_plan ap using(customer_id) where ap.customer_id is null ');

            $customerIds = Helper_Array::getCols($res, 'customer_id');
            if(count($customerIds)){
                $select->where('customer.customer_id in (?)', $customerIds);
            }else{
                $select->where('1=2');
            }
        }

        if($this->_context->email){
            $select->where('[mailAddresses.address] like ?','%'.$this->_context->email.'%');
        }

        // make sure the record is distinct
        $select->distinct();

        $page = $this->_context->page ? $this->_context->page : 1;
        $select->limitPage($page, 20);
        $pagination = $select->getPagination();

        $this->_view['customers'] = $select->getAll();
        $this->_view['pagination'] = $pagination;

    }

    function actionEdit()
    {
        $cid = $this->_context->cid;
        $c = Customer::findById($cid)->getOne();

        if ($this->_context->isPOST()) {
            try {
                $c->saveData($_POST);
                return $this->_redirect(url('.', 'cid/' . $c->id()));
            } catch (Exception $e) {
                $this->_view['errorMsg'] = '错误：' . $e->getMessage();
            }
        }

        if ($c->id()) {
            $this->_view['pageTitle'] = '客户资料编辑';
        } else {
            $this->_view['pageTitle'] = '新增客户';
        }

        $this->_view['customer'] = $c;
    }

    function actionSave()
    {
        $cid = $this->_context->customer_id;
        $c = Customer::findById($cid)->getOne();

        try {
            $c->saveData($_POST);
            $ret = array(
                'ack' => 'success',
                'customer' => array(
                    'customer_id' => $c->id(),
                ),
            );
        } catch (Exception $e) {
            $ret = array(
                'ack' => 'error',
                'msg' => $e->getMessage(),
            );
        }

        return json_encode($ret);
    }

    function actionRemove()
    {
        if ($this->_context->customer_id)
            $cid = $this->_context->customer_id;
        elseif ($this->_context->cid)
            $cid = $this->_context->cid;

        $c = Customer::findById($cid)->getOne();

        $isAjax = $this->_context->isAJAX();

        try {
            $c->destroy();

            if ($isAjax) {
                $ret = array(
                    'ack' => 'success',
                );
            }


        } catch (Exception $e) {
            if ($isAjax) {
                $ret = array(
                    'ack' => 'error',
                    'errorMsg' => $e->getMessage(),
                );
            }
        }

        if ($isAjax) {
            return json_encode($ret);
        } else {
            return $this->_redirect(url('/'));
        }
    }

    function actionAddMailAddress()
    {
        $cid = $this->_context->cid;
        $mailAddress = $this->_context->mailAddress;
        $c = Customer::findById($cid)->getOne();

        try {
            $newMailAddress = $c->addMailAddress($mailAddress);

            $ret = array(
                'ack' => 'success',
                'newMailAddress' => array(
                    'mail_address_id' => $newMailAddress->mail_address_id,
                    'address' => $newMailAddress->address,
                ),
            );
        } catch (Exception $e) {
            $ret = array(
                'ack' => 'error',
                'msg' => $e->getMessage(),
            );
        }

        return json_encode($ret);

    }

    function actionSetDefaultMailAddress()
    {
        $c = Customer::findById($this->_context->cid)->getOne();
        $c->setDefaultMailAddress($this->_context->mail_address_id);
        $c->save();

        $ret = array(
            'ack' => 'success'
        );

        return json_encode($ret);
    }

    function actionbindMailPlan()
    {
        $c = Customer::findById($this->_context->customer_id)->getOne();

        $para = array();

        if(isset($this->_context->bind_to_mail_address_id)){
            $para['bind_to_mail_address_id'] = $this->_context->bind_to_mail_address_id;
        }

        try {
            $newMailPlans = $c->bindMailPlan($this->_context->mail_plan_ids, $para);
            $newMailPlansData = array();

            foreach ($newMailPlans as $newMailPlan) {
                $newMailPlansData[] = array(
                    'mail_address_plan_id' => $newMailPlan->id(),
                    'mail_address_id' => $newMailPlan->mail_address_id,
                    'mail_address' => $newMailPlan->address(),
                    'mail_plan_id' => $newMailPlan->mail_plan_id,
                    'mail_plan_name' => $newMailPlan->plan->name,
                );
            }

            $ret = array(
                'ack' => 'success',
                'newMailPlans' => $newMailPlansData
            );
        } catch (Exception $e) {
            $ret = array(
                'ack' => 'error',
                'msg' => '您还没有为当前客户选择默认邮箱！',
            );
        }

        return json_encode($ret);

    }

    function actionUnbindMailPlan()
    {
        $map = Mail_Address_Plan::findById($this->_context->mail_address_plan_id)->getOne();
        if ($map->id()) $map->destroy();

        $ret = array(
            'ack' => 'success',
        );

        return json_encode($ret);
    }
}